<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Cms extends BaseController {

	public function __construct() {
        parent::__construct();
        // 后台初始化方法
        // $this->admin_init();

        // 后台标题
        $this->adminTitle = "管理系统";
        // 获取后台模块方法
        $this->menuLink = $this->router->fetch_class(). "/". $this->router->fetch_method();
        // $this->check_admin_menu_role($this->menuLink);
        // 获取数据
        $this->rmxUser = $this->session->rmxUser;               // 获取用户信息
        $this->userType = $this->rmxUser['user_type'];          // 获取角色身份
        // 如果是老师或者学校管理员
        if($this->userType == USER_TYPE_SCHOOL || $this->userType == USER_TYPE_TEACHER) {
            $this->rmxSchool = $this->rmxUser['school'];        // 获取学校信息
            $this->campusInfo = $this->session->campusInfo;     // 获取校区信息
            $this->campusList = $this->session->campusList;     // 获取校区列表
            if(!$this->campusInfo) throw new Exception("参数错误，请重新登录");
        }

        // 如果是超管，就跳转到超管的控制器
        if($this->userType != USER_TYPE_SCHOOL && $this->userType != USER_TYPE_TEACHER) show_error("参数错误，请重新登录");
        // 加载库
        $this->load->model('cmsModel');
    }

    // 跳转到首页
    public function redirectHzy() {
        $teacher = $this->rmxUser;
        echo '<pre>'; var_export($teacher);
    }

    // 文章管理
    public function index(){
        $this->url = 'index';

        // 获取文章栏目
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['getChild'] = true;
        $params['isDelete'] = 0;
        $params['parentId'] = 0;
        $this->categoryList = $this->cmsModel->get_category_list($params);

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "sub/cms". DIRECTORY_SEPARATOR. "index");
    }
    // 获取文章列表
    public function get_article_list(){
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        $totalParams['isDelete'] = 0;
        $total = $this->cmsModel->get_article_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        $data['isDelete'] = 0;
        $articleList = $this->cmsModel->get_article_list($data);
        foreach($articleList as &$article) {
            $categoryInfo = $this->cmsModel->get_category_info($article['category_id']);
            $article['categoryName'] = $categoryInfo['category_name'];
        }

        // 返回值
        exit(admin_table_data($total, $articleList));
    }
    // 发布文章页面
    public function article_edit($articleId = 0){
        $this->url = 'index';
        
        // 获取文章栏目
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['getChild'] = true;
        $params['parentId'] = 0;
        $params['isDelete'] = 0;
        $this->categoryList = $this->cmsModel->get_category_list($params);
        // 获取文章信息
        $this->articleInfo = $this->cmsModel->get_article_info($articleId);
        // 生成又拍云签名
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "sub/cms". DIRECTORY_SEPARATOR. "article_edit");
    }
    // 保存文章
    public function save_article_action(){
        $articleId = $this->post("id");
        $categoryId = $this->post("category_id");
        $title = $this->post("article_title");
        $cover = $this->post("article_cover");
        $content = $this->post("article_content", false);
        $sort = $this->post("article_sort");
        // 内容检查
        if(!$title) throw new Exception("文章标题不能为空");
        if(!$categoryId) throw new Exception("请选择文章栏目");
        if(!$content) throw new Exception("文章内容不能为空");
        // 入库
        $data['category_id'] = $categoryId;
        $data['article_title'] = $title;
        $data['article_cover'] = $cover;
        $data['article_content'] = $content;
        $data['article_sort'] = $sort;
        $data['updatetime'] = date("Y-m-d H:i:s");
        if($articleId) {
            // 获取栏目信息
            $articleInfo = $this->cmsModel->get_article_info($articleId);
            $this->check_data_valid($articleInfo, true, true, true, true);

            $this->db->update(CmsModel::$articleTable, $data, "id='{$articleId}'");
        } else {
            $data['school_id'] = $this->rmxSchool['id'];
            $data['campus_id'] = $this->campusInfo['id'];
            $data['createtime'] = $data['updatetime'];
            $this->db->insert(CmsModel::$articleTable, $data);
        }
        // 返回值
        $msg = $articleId ? '修改文章成功' : '添加文章成功';
        exit(json($msg, true));
    }
    // 删除文章
    public function delete_article_action(){
        $articleId = $this->post("id");
        $articleInfo = $this->cmsModel->get_article_info($articleId);
        $this->check_data_valid($articleInfo, true, true, true, true);

        // 执行删除操作
        $save['is_delete'] = 1;
        $this->db->update(CmsModel::$articleTable, $save, "id='{$articleId}'");
        exit(json("删除成功", true));
    }


    // 文章栏目
    public function category() {
        $this->url = 'category';

        // 获取文章栏目
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['getChild'] = true;
        $params['parentId'] = 0;
        $params['isDelete'] = 0;
        $this->categoryList = $this->cmsModel->get_category_list($params);

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "sub/cms". DIRECTORY_SEPARATOR. "category");
    }
    // 文章栏目编辑
    public function category_edit($categoryId = 0){
        $this->url = 'category';
        
        $this->categoryInfo = $this->cmsModel->get_category_info($categoryId);
        // 获取一级栏目
        $cateParams['schoolId'] = $this->rmxSchool['id'];
        $cateParams['campusId'] = $this->campusInfo['id'];
        $cateParams['parentId'] = 0;
        $cateParams['isDelete'] = 0;
        $this->categoryList = $this->cmsModel->get_category_list($cateParams);

        // 生成又拍云签名
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceParams = $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "sub/cms". DIRECTORY_SEPARATOR. "category_edit");
    }

    // 保存文章栏目
    public function save_category_action(){
        $categoryId = $this->post("id");
        $categoryName = $this->post("category_name");
        $categorySort = $this->post("category_sort");
        $categoryRecommend = $this->post("category_recommend");
        $parentId = $this->post("parent_id");
        $categoryType = $this->post("category_type");               // 栏目类型
        $articleCover = $this->post("category_article_cover");      // 栏目封面
        $articleContent = $this->post("category_article_content", false);  // 栏目内容
        // print_r($articleContent);exit;
        // 内容检查
        if(!$categoryName) throw new Exception("栏目名称不能为空");
        if($categoryType == CMS_CATEGORY_ARTICLE && !$articleContent) throw new Exception("请填写文章内容");

        // 获取父栏目信息
        $categoryTree = array();
        if($parentId) {
            $parentInfo = $this->cmsModel->get_category_info($parentId);
            $categoryTree = explode(",", $parentInfo['category_tree']);
        }
        $categoryTree[] = $parentId;
        // 入库
        $data['category_name'] = $categoryName;
        $data['category_recommend'] = $categoryRecommend;
        $data['category_sort'] = $categorySort;
        $data['category_type'] = $categoryType;
        $data['category_article_cover'] = $articleCover;
        $data['category_article_content'] = $articleContent;
        $data['updatetime'] = date("Y-m-d H:i:s");
        if($categoryId) {
            // 获取栏目信息
            $categoryInfo = $this->cmsModel->get_category_info($categoryId);
            $this->check_data_valid($categoryInfo, true, true, true, true);

            $this->db->update(CmsModel::$categoryTable, $data, "id='{$categoryId}'");
        } else {
            $data['school_id'] = $this->rmxSchool['id'];
            $data['campus_id'] = $this->campusInfo['id'];
            $data['parent_id'] = $parentId;
            $data['category_tree'] = implode(",", $categoryTree);
            $data['createtime'] = $data['updatetime'];
            $this->db->insert(CmsModel::$categoryTable, $data);
        }
        // 返回值
        $msg = $categoryId ? '修改网站栏目成功' : '添加网站栏目成功';
        exit(json($msg, true));
    }
    // 删除栏目
    public function delete_category_action(){
        $categoryId = $this->post("id");
        $categoryInfo = $this->cmsModel->get_category_info($categoryId);
        $this->check_data_valid($categoryInfo, true, true, true, true);
        // 执行删除操作
        $where = "`id`='{$categoryId}' OR FIND_IN_SET('{$categoryId}', `category_tree`)";
        $save['is_delete'] = 1;
        $this->db->update(CmsModel::$categoryTable, $save, $where);
        exit(json("删除成功", true));
    }
    // 轮播图管理
    public function slider(){
        $this->url = 'slider';
        // 生成又拍云签名
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceParams = $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);

        // 获取数据
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        $data['isDelete'] = 0;
        $this->sliderList = $this->cmsModel->get_slider_list($data);
        
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "sub/cms". DIRECTORY_SEPARATOR. "slider");
    }
    // 获取轮播图列表
    public function get_slider_list(){
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        $totalParams['isDelete'] = 0;
        $total = $this->cmsModel->get_slider_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        $data['isDelete'] = 0;
        $sliderList = $this->cmsModel->get_slider_list($data);
        // 返回值
        exit(admin_table_data($total, $sliderList));
    }
    // 保存轮播图
    public function save_slider_action(){
        $sliderId = $this->post('id');
        $sliderImage = $this->post("slider_image");
        $sliderTitle = $this->post('slider_title');
        $sliderSort = $this->post("slider_sort");
        $sliderLink = $this->post("slider_link");
        // 内容检查
        if(!$sliderImage) throw new Exception("请上传幻灯片内容");
        // 入库
        $data['slider_image'] = $sliderImage;
        $data['slider_name'] = $sliderTitle;
        $data['slider_link'] = $sliderLink;
        $data['slider_sort'] = $sliderSort;
        $data['updatetime'] = date("Y-m-d H:i:s");
        if($sliderId) {
            $this->db->update(CmsModel::$sliderTable, $data, "id='{$sliderId}'");
        } else {
            $data['school_id'] = $this->rmxSchool['id'];
            $data['campus_id'] = $this->campusInfo['id'];
            $data['createtime'] = $data['updatetime'];
            $this->db->insert(CmsModel::$sliderTable, $data);
        }
        // 返回值
        $msg = $sliderId ? '修改网站轮播图成功' : '添加网站轮播图成功';
        exit(json($msg, true));
    }
    // 删除轮播图
    public function delete_slider_action(){
        $sliderId = $this->post("id");
        // 执行删除操作
        $save['is_delete'] = 1;
        $this->db->update(CmsModel::$sliderTable, $save, "id='{$sliderId}'");
        exit(json("删除成功", true));
    }

    // 友情链接
    public function link(){
        $this->url = 'link';
        // 生成又拍云签名
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceParams = $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);

        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        $data['isDelete'] = 0;
        $this->linkList = $this->cmsModel->get_link_list($data);

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "sub/cms". DIRECTORY_SEPARATOR. "link");
    }
    // 获取友情链接列表
    public function get_link_list(){
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        $totalParams['isDelete'] = 0;
        $total = $this->cmsModel->get_link_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        $data['isDelete'] = 0;
        $linkList = $this->cmsModel->get_link_list($data);
        // 返回值
        exit(admin_table_data($total, $linkList));   
    }
 

    // 设置界面
    public function setting(){
        $this->url = 'setting';

        // 生成又拍云签名
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);

        $this->setting = $this->cmsModel->get_cms_setting($this->rmxSchool['id'], $this->campusInfo['id']);
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "sub/cms". DIRECTORY_SEPARATOR. "setting");
    }
    // 保存官网设置
    public function save_cms_setting(){
        $cmsLogo = $this->post("cms_logo");
        $cmsCategoryBanner = $this->post("cms_category_banner");
        $cmsContent = $this->post("cms_content", false);
        $cmsAddress = $this->post("cms_address");
        $cmsMobile = $this->post("cms_mobile");
        $cmsPosition = $this->post("cms_position");
        $cmsThemeColor = $this->post("cms_theme_color");

        // 内容检查
        if(!$cmsLogo) throw new Exception("请上传官网LOGO");
        if(!$cmsContent) throw new Exception("请填写学校简介");
        if(!$cmsAddress) throw new Exception("请填写学校通讯地址");
        if(!$cmsMobile) throw new Exception("请填写学校联系电话");

        // 设置信息
        $setting = $this->cmsModel->get_cms_setting($this->rmxSchool['id'], $this->campusInfo['id']);

        // 入库
        $data['cms_logo'] = $cmsLogo;
        $data['cms_category_banner'] = $cmsCategoryBanner;
        $data['cms_content'] = $cmsContent;
        $data['cms_address'] = $cmsAddress;
        $data['cms_mobile'] = $cmsMobile;
        $data['cms_position'] = $cmsPosition;
        $data['cms_theme_color'] = $cmsThemeColor;
        $data['updatetime'] = date("Y-m-d H:i:s");
        if($setting) {
            $this->db->update(CmsModel::$settingTable, $data, "id='{$setting['id']}'");
        } else {
            $data['school_id'] = $this->rmxSchool['id'];
            $data['campus_id'] = $this->campusInfo['id'];
            $data['cms_token'] = md5($this->rmxSchool['id']. "_". $this->campusInfo['id']);
            $data['createtime'] = $data['updatetime'];
            $this->db->insert(CmsModel::$settingTable, $data);
        }
        // 返回值
        exit(json("保存官网设置成功", true));
    }

}